package org.example.day10;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 4.1.2: 使用ReentrantLock实现同步 测试2
 */
public class MyThread6 {
    //方法A 和 方法B 用的是同一把锁
    private Lock lock = new ReentrantLock();
    public void methodA(){
        try {
            lock.lock();
            System.out.println("methodA begin Threadname = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println("methodA end Threadname = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void methodB(){
        try {
            lock.lock();
            System.out.println("methodB begin Threadname = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println("methodB end Threadname = " + Thread.currentThread().getName() + " time = " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread6 m6 = new MyThread6();
        Thread6A ta = new Thread6A(m6);
        ta.setName("A");
        ta.start();
        Thread6AA taa = new Thread6AA(m6);
        taa.setName("AA");
        taa.start();
        Thread.sleep(100);
        Thread6B tb = new Thread6B(m6);
        tb.setName("B");
        tb.start();
        Thread6BB tbb = new Thread6BB(m6);
        tbb.setName("BB");
        tbb.start();
    }
}

class Thread6A extends Thread{
    private MyThread6 m6;

    public Thread6A(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.methodA();
    }
}

class Thread6AA extends Thread{
    private MyThread6 m6;

    public Thread6AA(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.methodA();
    }
}

class Thread6B extends Thread{
    private MyThread6 m6;

    public Thread6B(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.methodB();
    }
}


class Thread6BB extends Thread{
    private MyThread6 m6;

    public Thread6BB(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        m6.methodB();
    }
}